<?php

// +----------------------------------------------------------------------
// | E-SEES [ FAST AND SIMPLE TRANSPARENT TRACE TO ITS SOURCE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.e-sees.com All rights reserved.
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
 
namespace Admin\Controller;
use Think\Controller;
use Org\Net\UploadFile;
use Common\Api\WXChat;
/*
 * 全局控制器
 * */
class BaseController extends Controller {
    public  $dbprefix="";
    /**
     * 前台控制器初始化
     */
    protected function _initialize(){


        //define("TOKEN",'aomai');  //在配置文件里设置了
        define("UID",$_SESSION['admin_id']);
        $this->dbprefix=C('DB_PREFIX');


		$uid=$_SESSION['admin_id'];
		if(!$uid){

			if(IS_AJAX){

				$this->error("登录已失效，请刷新界面重新登录");
				exit;

			}
 
			header("Location: /am/privilege.php?act=login");
			exit;
		}
		define("TOKEN",'aomai');
		define("UID",$uid);

//		echo($rule  = strtolower(CONTROLLER_NAME.'/'.ACTION_NAME));
		//如果id等于1就是超级管理员
		if($uid==1){
			return true;
		}

		if($this->checkUser($uid)){
			if(IS_AJAX){
				$this->error("Access Denied!");
				exit;
			}else{
				$this->noauth("Access Denied!");
			}
		}
    }

 

	/**
	 * 权限验证方法
	 * @param $uid
	 * @return bool
	 */
	public  function  checkUser($uid){
		//获取访问的控制器名称和方法名称
		$rule  = strtolower(CONTROLLER_NAME.'/'.ACTION_NAME);
		//获取登录用户的访问权限
		$auth_ruleStr=empty($_SESSION["admin_rules"])?"":$_SESSION["admin_rules"];
		$flag=true;
		if (strpos(strtolower($auth_ruleStr),strtolower($rule)) !== false ){
			$flag=false;
		}
		return $flag;
	}

	/**
	 * write by nirunfa 2015-08-07
	 * update by 2015-12-19
	 * @param $modelstr  模型字符或模型对象
	 * @param $_where_order_field where条件,order排序,field查询字段 ,join联表查询数组,having 用于别名操作
	 * @param string $count 查询条数字段
	 */
	public function _getListsFromModel($modelstr,$_where_order_field=array(),$count='count(*) as tp_count'){
		$_where=$where=$_where_order_field['where'];
		$field=empty($_where_order_field['field'])?true:$_where_order_field['field'];
		$order=$_where_order_field['order'];
		$_join = $join = $_where_order_field['join'];
		$alias=$_where_order_field["alias"];
		$having = $_where_order_field['having'];
		$count_where=$_where_order_field['count_where'];
		$listrows=empty($_where_order_field['listrows'])?20:$_where_order_field['listrows'];
		$group=$_where_order_field["group"];
		$is_group_count = intval($_where_order_field['is_group_count']);

		$model = $modelstr;
		if(is_string($model)){
			$model=M($model);
		}

		//可以自定义内容 id
		$element_id = !empty($_where_order_field['id'])?$_where_order_field['id']:'load_tb_div';
		if($is_group_count === 1){
			$_join = $_where_order_field['count_join'];
			$_where = $_where_order_field['count_where'];
		}

		$count_=$model->alias($alias)->where($_where)->join($_join)->field($count)->find();


		//总条数
		$sum =$count_['tp_count'];

		//当前页
		$current_page=I('request.p',1,'intval');

		//_page select跳转页数
		$_page=I('request._page');
		if(!empty($_page)){
			$current_page=$_page;
		}


		//总页数
		$pages=ceil($sum/$listrows);

		$limit=(($current_page-1)*$listrows).','.$listrows;

		$_lists = $model->alias($alias)->where($where)->join($join)->order($order)->field($field)->group($group)->having($having)->limit($limit)->select();


		if($pages<=5){
			for($i=1;$i<$pages+1;$i++){
			$options.="<option value='{$i}'>{$i}</option>";
			}
			/* $options.='<option value=\'2\'>2</option>
                       <option value=\'3\'>3</option>
                       <option value=\'4\'>4</option>
                       <option value=\'5\'>5</option>'; */
		}else{
			$options='<option value=\'1\'>1</option>';
			if($pages<=25){
				$options.='<option value=\'2\'>2</option>
                       <option value=\'3\'>3</option>
                       <option value=\'4\'>4</option>
                       <option value=\'5\'>5</option>';
				$options.="<option value='{$pages}'>{$pages}</option>";
			}else{
				$options.="<option value='25'>25</option>";
				if($pages>50){
					$options.="<option value='50'>50</option>";
				}
				if($pages>75){
					$options.="<option value='75'>75</option>";
				}

				$options.="<option value='{$pages}'>{$pages}</option>";
			}
		}

		$options=str_replace(">{$_page}<"," selected >{$_page}<",$options);

		$page_html="<table style='margin-bottom:25px;'><tbody><tr><td class='optd'>共<i class='blue'>{$sum}</i>条记录,&nbsp;当前显示第<i class='blue'>{$current_page}</i>页,&nbsp;";
		$page_html.="每页<input type='text'  style='width: 50px;min-height:15px;' value='{$listrows}' id='verypageshowcount' name='_listrows' class='verypageshowcount' onblur='inputGoToPage(this,\"{$element_id}\");' />.";
		$page_html.="跳转到第<select style='width: 45px;height: 25px;line-height: 25px;' name='gotoPage' class='gotoPage' id='gotoPage' onchange='selectGoToPage(this,\"{$element_id}\");'>{$options}</select></td>";

		$lis="<li class='paginItem first_li first'><a href='{$this->url(1)}'onclick='return goPage(this,\"{$element_id}\");'>第一页</a></li>";

		$up_rows=$current_page-1;
		$lis.="<li class='paginItem prev_li prev'><a href='{$this->url($up_rows)}'onclick='return goPage(this,\"{$element_id}\");'>上一页</a></li>";

		//显示范围
		$range=5;
		//数字连接
		$link_page = "";

		//第一页linenumber
		if($pages>$range && $current_page>=$range){
			$link_page.="<li class='paginItem'><a href='{$this->url(1)}'onclick='return goPage(this,\"{$element_id}\");'>1</a></li>
    		<li class='paginItem more'><a href='javascript:;'>...</a></li>";
		}

		for($i = 1; $i <= $pages; $i++){
			$page = $i;

			//如果当前页小于每页显示范围
			//就相当于1-每页显示范围内条数，1 2 3至每页显示范围 ... 最后一页

			//如果当前页大于等于每页显示范围
			//就以每页显示范围为中心，1...前面两个+每页显示范围+后面两个...最后一页

			if($current_page<$range){
				if($page > 0 && $page != $current_page){
					if($page <= $range){
						$link_page .= "<li class='paginItem'><a href='{$this->url($page)}' onclick='return goPage(this,\"{$element_id}\");'>{$page}</a></li>";
					}else{
						if(ceil($page)===$pages){
							$link_page .='&nbsp;<li class="paginItem more"><a href="javascript:;">...</a></li>';
						}elseif($page>$pages){
							break;
						}else{
							continue;
						}
					}
				}else{
					if($page > 0 && $pages != 1){
						$link_page .= "<li rhref='{$this->url($page)}' class='paginItem current datalist_current_ahref'><a href='javascript:;'>{$page}</a></li>";
					}
				}
			}else{
				if($page > 0 && $page != $current_page){
					//这个情况处理特殊
					//1.当前页是倒数第二页
					//2.中间页数
					//3.最后一页
					//                        if($page+4>=$pages && $page==$current_page){
					//                              continue;
					//                        }

					if(( ($page <= $current_page+2 && $page>=$current_page-2) ||
						($current_page+1==$pages && $page <= $current_page+1 && $page>=$current_page-3) ||
						($current_page==$pages && $page>=$current_page-4) ) ){
						$link_page .= "<li class='paginItem'><a href='{$this->url($page)}'onclick='return goPage(this,\"{$element_id}\");'>{$page}</a></li>";
					}else{
						if($page===1){
							$link_page.='&nbsp;';
						}elseif(ceil($page)===$pages){
							$link_page .='<li class="paginItem more"><a href="javascript:;">...</a></li>';
						}elseif(ceil($page)>$pages){
							break;
						}else{
							continue;
						}
					}
				}else{
					if($page > 0 && $pages != 1){
						$link_page .= "<li rhref='{$this->url($page)}' class='paginItem current datalist_current_ahref'><a href='javascript:;'>{$page}</a></li>";
					}
				}
			}
		}

		if($pages>$range && ($pages-$current_page)>5 ){
			$link_page.="<li class='paginItem'><a href='{$this->url($pages)}'onclick='return goPage(this,\"{$element_id}\");'>{$pages}</a></li>";
		}


		$lis.=$link_page;

		$down_rows=($current_page+1)>$pages?0:($current_page+1);
		$lis.="<li class='paginItem next_li next'><a href='{$this->url($down_rows)}'onclick='return goPage(this,\"{$element_id}\");'>下一页</a></li>";

		$lis.="<li class='paginItem last_li last'><a href='{$this->url($pages)}' onclick='return goPage(this,\"{$element_id}\");'>最后一页</a></li>";

		$a_html="<td><ul class='paginList'>{$lis}</ul></td>";
		$page_html.=$a_html;

		$page_html.='</tr></tbody></table>';

		$page_data=array(
			'firstRow'=>(($current_page-1)*$listrows),
			'page'=>$current_page,
			'totalPages'=>$sum,
			'page_size'=>$listrows,
			'lists'=>$_lists,
			'page_html'=>$page_html, 
		);

		return $page_data;
	}


	/**
	 * 生成链接URL
	 * @param  integer $page 页码
	 * @return string
	 */
	private function url($page){
		if(empty($page)){
			return 'javascript:;';
		}
		$_post_query_data=(array)I('post.');
		$_get_query_data=(array)I('get.');
		$_query_data  = array_merge($_post_query_data,$_get_query_data);
		$_query_data['p']=$page;
		unset($_query_data['_page']);
		return U(ACTION_NAME, $_query_data);
	}
	
	
	
	public function upload() { 
		$upload = new UploadFile (); // 实例化上传类
		$upload->maxSize = 2048000; // 设置附件上传大小
		$upload->allowExts = array (
				'jpg',
				'gif',
				'png',
				'jpeg'
		); // 设置附件上传类型
	
		$folder= date("Y")."/".date("Y-m")."/";
		$upload->savePath ='./Public/Uploads/'.$folder; // 设置附件上传目录
		if (! $upload->upload ()) { // 上传错误提示错误信息
			$this->error ( $upload->getErrorMsg () );
		} else { // 上传成功 获取上传文件信息
			$info = $upload->getUploadFileInfo ();
			foreach($info as $k=>$v){
				$v['savename']=$folder.$v['savename'];
				$fileinfo[$k]=$v;
			}
		}
		return $fileinfo;
	}
	
	public function uploadfile($folder='',$ext='',$maxsize=0) {
		
		$upload = new UploadFile (); // 实例化上传类
		$upload->maxSize = ($maxsize>0)?$maxsize:5120000; // 设置附件上传大小
		$upload->allowExts = (is_array($ext) && count($ext)>0) ? $ext: array (
				'jpg',
				'gif',
				'png',
				'jpeg'
		); // 设置附件上传类型
			
		$upload->savePath = './Public/Uploads/'.((!empty($folder))? $folder:""); // 设置附件上传目录
		if (! $upload->upload ()) { // 上传错误提示错误信息
			$this->error ( $upload->getErrorMsg () );
		} else { // 上传成功 获取上传文件信息
			$info = $upload->getUploadFileInfo ();
			foreach($info as $k=>$v){
				$v['savename']= $folder.$v['savename'];
				$fileinfo[$k]=$v;
			}
		}
		return $fileinfo;
	}

    
    //初始化类
    public function init()
    {
    	$options = array (
    			'token' => C("SetUrlTOKEN"), // 填写你设定的key
    			'encodingaeskey' => C("encodingaeskey"), // 填写加密用的EncodingAESKey
    			'appid' => C("APPID"), // 填写高级调用功能的app id
    			'appsecret' =>C("APPSecret"), // 填写高级调用功能的密钥
    	);
    	$wxObj = new WXChat( $options );
    	return $wxObj;
    }
    
    //菜单重构信息
    public function createwxmune($result=array())
    {
    	$arymenu=array();
    	foreach($result as $k=>$v)
    	{
    		if($v['pid']==0)
    		{
    			$data=array();
    			$data['name']= $v['mname'];
    			if(!empty($v['url'])){
    				$data['type']='view';
    				$data['url']=$v['url'];
    			}
    			else
    			{
    				$data['type']='click';
    				$data['key']=$v['key'];
    			}
    				
    			//子级菜单
    			$sub_but=array();
    			foreach($result as $key=>$vs)
    			{
    				$temp=array();
    				if($vs['pid']==$v['menuid'])
    				{
    					$temp['name']=$vs['mname'];
    					if($vs['url']!=''){
    						$temp['type']='view';
    						$temp['url']=$vs['url'];
    					}
    					else
    					{
    						$temp['type']='click';
    						$temp['key']=$vs['key'];
    					}
    				}
    				if(count($temp)>0)
    					$sub_but[]=$temp;
    			}
    			if(count($sub_but)>0)
    				$data['sub_button']=$sub_but;
    				
    			$arymenu['button'][]= $data;
    		}
    	}
    	return $arymenu;
    }
	
		public function _getListsViewSpecial($modelstr,$_where_order_field=array(),$count='count(*) as tp_count'){
    	$where=$_where_order_field['where'];
    	$field=empty($_where_order_field['field'])?true:$_where_order_field['field'];
    	$order=$_where_order_field['order'];
    	$join=$_where_order_field['join'];
        $alias=$_where_order_field["alias"];
    	$having = $_where_order_field['having'];
    	$count_where=$_where_order_field['count_where'];
    	$listrows=empty($_where_order_field['listrows'])?20:$_where_order_field['listrows'];
        $group=$_where_order_field["group"];
    	$model = $modelstr;
    	if(is_string($model)){
    		$model=M($model);
    	}
    
    	//可以自定义内容 id
    	$element_id = !empty($_where_order_field['id'])?$_where_order_field['id']:'load_tb_div';
    	$count_=$model->alias($alias)->where($where)->join($join)->order($order)->field($count)->group($group)->having($having)->find();
        //echo $model->getLastSql();
    	//总条数
    	$sum =$count_['tp_count'];
    	//当前页
    	$current_page=I('request.p',1,'intval');
    
    	//_page select跳转页数
    	$_page=I('post._page');
    	if(!empty($_page)){
    		$current_page=$_page;
    	}
    
    
    	//总页数
    	$pages=ceil($sum/$listrows);
    	$limit=(($current_page-1)*$listrows).','.$listrows;
		if($modelstr == 'wechat_users')
		{    $Model = new \Think\Model();
			 $sql="select *,fn_get_wx_user_count(id) as total from ki_".$modelstr." where ".$where." order by ".$order." limit ".$limit;
			 $_lists=$Model->query($sql);
		}
		else
		{
		
    	     $_lists = $model->alias($alias)->where($where)->join($join)->order($order)->field($field)->group($group)->having($having)->limit($limit)->select();
        }
//    	       echo $model->getLastSql();
    	//       die;
    	//       die;
    	$options='<option value=\'1\'>1</option>';
    
    	if($pages<=5){
			for($i=0;$i<$pages-1;$i++)
			{
				$options.='<option value=\''.($i+2).'\'>'.($i+2).'</option>';
			}
    		
    	}else{
    		if($pages<=25){
    			$options.='<option value=\'2\'>2</option>
                       <option value=\'3\'>3</option>
                       <option value=\'4\'>4</option>
                       <option value=\'5\'>5</option>';
    			$options.="<option value='{$pages}'>{$pages}</option>";
    		}else{
    			$options.="<option value='25'>25</option>";
    			if($pages>50){
    				$options.="<option value='50'>50</option>";
    			}
    			if($pages>75){
    				$options.="<option value='75'>75</option>";
    			}
    
    			$options.="<option value='{$pages}'>{$pages}</option>";
    		}
    	}
    
    	$options=str_replace(">{$_page}<"," selected >{$_page}<",$options);

    	$page_html="<table style='margin-bottom:15px;'><tbody><tr><td class='optd'>共<i class='blue'>{$sum}</i>条记录,&nbsp;当前显示第<i class='blue'>{$current_page}</i>页,共<b class='red'>{$pages}</b>页&nbsp;";
    	$page_html.="每页<input type='text'  style='width: 50px;min-height:15px;' value='{$listrows}'onblur='inputGoToPages(this);' />.";
    	$page_html.="跳转到第<select style='width: 45px;height: 25px;line-height: 25px;' onchange='selectGoToPages(this);'>{$options}</select></td>";

    	$lis="<li class='paginItem first_li first'><a href='{$this->url(1)}'>第一页</a></li>";

    	$up_rows=$current_page-1;
    	$lis.="<li class='paginItem prev_li prev'><a href='{$this->url($up_rows)}'>上一页</a></li>";

    	//显示范围
    	$range=5;
    	//数字连接
    	$link_page = "";

    	//第一页linenumber
    	if($pages>$range && $current_page>=$range){
    		$link_page.="<li class='paginItem'><a href='{$this->url(1)}'>1</a></li>
    		<li class='paginItem more'><a href='javascript:;'>...</a></li>";
    	}

    	for($i = 1; $i <= $pages; $i++){
    		$page = $i;

    		//如果当前页小于每页显示范围
    		//就相当于1-每页显示范围内条数，1 2 3至每页显示范围 ... 最后一页

    		//如果当前页大于等于每页显示范围
    		//就以每页显示范围为中心，1...前面两个+每页显示范围+后面两个...最后一页

    		if($current_page<$range){
    			if($page > 0 && $page != $current_page){
    				if($page <= $range){
    					$link_page .= "<li class='paginItem'><a href='{$this->url($page)}'>{$page}</a></li>";
    				}else{
    					if(ceil($page)===$pages){
    						$link_page .='&nbsp;<li class="paginItem more"><a href="javascript:;">...</a></li>';
    					}elseif($page>$pages){
    						break;
    					}else{
    						continue;
    					}
    				}
    			}else{
    				if($page > 0 && $pages != 1){
    					$link_page .= "<li rhref='{$this->url($page)}' class='paginItem current datalist_current_ahref'><a href='javascript:;'>{$page}</a></li>";
    				}
    			}
    		}else{
    			if($page > 0 && $page != $current_page){
    				//这个情况处理特殊
    				//1.当前页是倒数第二页
    				//2.中间页数
    				//3.最后一页
    				//                        if($page+4>=$pages && $page==$current_page){
    				//                              continue;
    				//                        }

    				if(( ($page <= $current_page+2 && $page>=$current_page-2) ||
    						($current_page+1==$pages && $page <= $current_page+1 && $page>=$current_page-3) ||
    						($current_page==$pages && $page>=$current_page-4) ) ){
    					$link_page .= "<li class='paginItem'><a href='{$this->url($page)}'>{$page}</a></li>";
    				}else{
    					if($page===1){
    						$link_page.='&nbsp;';
    					}elseif(ceil($page)===$pages){
    						$link_page .='<li class="paginItem more"><a href="javascript:;">...</a></li>';
    					}elseif(ceil($page)>$pages){
    						break;
    					}else{
    						continue;
    					}
    				}
    			}else{
    				if($page > 0 && $pages != 1){
    					$link_page .= "<li class='paginItem current'><a href='javascript:;'>{$page}</a></li>";
    				}
    			}
    		}
    	}

    	if($pages>$range && ($pages-$current_page)>5 ){
    		$link_page.="<li class='paginItem'><a href='{$this->url($pages)}'>{$pages}</a></li>";
    	}


    	$lis.=$link_page;

    	$down_rows=($current_page+1)>$pages?0:($current_page+1);
    	$lis.="<li class='paginItem next_li next'><a href='{$this->url($down_rows)}'>下一页</a></li>";

    	$lis.="<li class='paginItem last_li last'><a href='{$this->url($pages)}'>最后一页</a></li>";
    
    	$a_html="<td><ul class='paginList'>{$lis}</ul></td>";
    	$page_html.=$a_html;
    
    	$page_html.='</tr></tbody></table>';
    
    	$page_data=array(
    			'firstRow'=>(($current_page-1)*$listrows),
    			'page'=>$current_page,
    			'totalPages'=>$sum,
    			'page_size'=>$listrows,
    			'lists'=>$_lists,
    			'page_html'=>$page_html,
    	);

    	return $page_data;
    }
	

    /**
     * 生成链接URL
     * @param  integer $page 页码
     * @return string
     */
   /*  private function url($page){
    	if(empty($page)){
    		return 'javascript:;';
    	}
    	$_query_data=(array)I('request.');
    	$_query_data['p']=$page;
    	return U(ACTION_NAME, $_query_data);
    } */
}